﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Text;

namespace OpenCvSharpExtension
{
    /// <summary>
    ///轮廓图形匹配
    /// </summary>
    /// <remarks>https://www.cnblogs.com/little-monkey/p/7475481.html</remarks>
    public class ShapeMatchHelper
    {
        /// <summary>
        /// 查找轮廓
        /// </summary>
        /// <param name="img"></param>
        /// <param name="thresh">图像二值化处理时的阈值，0-255</param>
        /// <param name="mode"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static Point[][] findContours(Mat img, double thresh = 100, RetrievalModes mode = RetrievalModes.Tree, ContourApproximationModes method = ContourApproximationModes.ApproxNone)
        {
            using (Mat temp = img.CvtColor(ColorConversionCodes.BGR2GRAY))//灰度处理
            {
                Cv2.Threshold(temp, temp, thresh, 255, ThresholdTypes.Binary);//二值化处理  //二值化的另一个方法Canny()

                Point[][] contours;
                HierarchyIndex[] hierarcy;
                Cv2.FindContours(temp, out contours, out hierarcy, mode, method);
                return contours;
            }

        }
        /// <summary>
        /// 匹配轮廓
        /// </summary>
        /// <param name="tempContour">模板轮廓</param>
        /// <param name="targetContours">目标轮廓集合</param>  
        /// <param name="matchRateThresh">相轮廓似度阈值，轮廓匹配时，matchRate值越小表示相似度越高</param>
        /// <returns>返回所有匹配的轮廓</returns>
        public static Point[][] Match(Point[] tempContour, Point[][] targetContours, double matchRateThresh = 0.1)
        {
            List<Point[]> ms = new List<Point[]>();
            for (int i = 0; i < targetContours.Length; i++)
            {
                var matchRate = Cv2.MatchShapes(tempContour, targetContours[i], ShapeMatchModes.I1);//匹配轮廓 值越小相似度越高
                if (matchRate <= 0.2)
                {
                    ms.Add(targetContours[i]);
                    //if (debugImg != null)
                    //{//绘制轮廓
                    //    Cv2.DrawContours(debugImg, targetContours, i, new Scalar(0, 255, 0), 2, LineTypes.Link8);
                    //}

                }
            }
            return ms.ToArray();
        }
    }
}
